<template>
  <ele-page
    flex-table
    :multi-card="false"
    hide-footer
    style="min-height: 420px"
  >
    <ele-card
      flex-table
      :body-style="{ padding: '0 0 0 16px', overflow: 'hidden' }"
    >
      <ele-split-panel
        ref="splitRef"
        flex-table
        size="300px"
        allow-collapse
        :custom-style="{ borderWidth: '0 1px 0 0', padding: '16px 0' }"
        :body-style="{ padding: '16px 16px 0 0', overflow: 'hidden' }"
        :style="{ height: '100%', overflow: 'visible' }"
      >
        <div style="padding: 0 16px 12px 0">
          <el-input
            clearable
            :maxlength="20"
            v-model="keywords"
            placeholder="输入字典名称搜索"
            :prefix-icon="SearchOutlined"
          />
        </div>
        <div style="margin-bottom: 12px">
          <el-button
            type="primary"
            class="ele-btn-icon"
            :icon="PlusOutlined"
            @click="openAdd()"
          >
            新建
          </el-button>
          <el-button
            type="primary"
            underline="never"
            @click="openView(current)"
          >
            查看
          </el-button>
          <el-button
            type="warning"
            :disabled="!current"
            class="ele-btn-icon"
            :icon="EditOutlined"
            @click="openEdit(current)"
          >
            修改
          </el-button>

          <el-button
            type="danger"
            :disabled="!current"
            class="ele-btn-icon"
            :icon="DeleteOutlined"
            @click="remove('remove', current)"
          >
            删除
          </el-button>
        </div>
        <ele-loading
          :loading="loading"
          :style="{ flex: 1, paddingRight: '16px', overflow: 'auto' }"
        >
          <el-tree
            ref="treeRef"
            :data="data"
            highlight-current
            node-key="dict_id"
            :props="{ label: 'dict_name' }"
            :expand-on-click-node="false"
            :default-expand-all="true"
            :filter-node-method="filterNode"
            :style="{
              '--ele-tree-item-height': '34px',
              '--ele-tree-expand-padding': 0,
              '--ele-tree-expand-margin': 0,
            }"
            @node-click="handleNodeClick"
          >
            <template #default="{ data: d }">
              <div
                class="el-tree-node__label"
                style="display: flex; align-items: center"
              >
                <div style="margin-right: 4px">{{ d.dict_name }}</div>
                <div style="font-size: 12px; opacity: 0.8; font-weight: normal">
                  ({{ d.dict_code }})
                </div>
              </div>
            </template>
          </el-tree>
        </ele-loading>
        <template #body>
          <dict-data-list
            v-if="current && current.dict_id"
            :dict_id="current.dict_id"
          />
        </template>
      </ele-split-panel>
    </ele-card>

    <!-- 新增 -->
    <dict-edit action="add" v-model="showAdd" @done="query" />

    <!-- 修改 -->
    <dict-edit action="edit" :data="current" v-model="showEdit" @done="query" />

    <!-- 查看 -->
    <dict-edit action="view" :data="current" v-model="showView" />
  </ele-page>
</template>

<script setup>
import { ref, nextTick, watch } from "vue";
import { EleMessage } from "ele-admin-plus/es";
import { useModal } from "@/hooks/useModal";

// 在文件顶部导入useOperator
import { useOperator } from "@/hooks/operator";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
} from "@/components/icons";
import { useMobile } from "@/utils/use-mobile";
import DictDataList from "./components/dict-data-list.vue";
import DictEdit from "./components/dict-edit.vue";
import { listDictionaries, removeDictionary } from "@/api/system/dictionary";

defineOptions({ name: "SystemDictionary" });

/** 是否是移动端 */
const { mobile } = useMobile();

/** 分割面板组件 */
const splitRef = ref(null);

/** 树组件 */
const treeRef = ref(null);

/** 加载状态 */
const loading = ref(true);

/** 树形数据 */
const data = ref([]);

/** 选中数据 */
const current = ref(null);

/** 机构搜索关键字 */
const keywords = ref("");

/** 是否显示编辑弹窗 */
// const showEdit = ref(false);

/** 查询 */
const query = () => {
  loading.value = true;
  listDictionaries()
    .then((list) => {
      loading.value = false;
      data.value = list ?? [];
      nextTick(() => {
        handleNodeClick(data.value[0]);
      });
    })
    .catch((e) => {
      loading.value = false;
      EleMessage.error(e.message);
    });
};

/** 选择数据 */
const handleNodeClick = (row) => {
  // 移动端自动收起左侧
  if (current.value != null && mobile.value) {
    splitRef.value?.toggleCollapse?.(true);
  }
  if (row && row.dict_id) {
    current.value = row;
    treeRef.value?.setCurrentKey?.(row.dict_id);
  } else {
    current.value = null;
  }
};

// 使用hook创建各个弹窗
const { visible: showAdd, open: openAdd } = useModal({
  beforeOpen: async () => {
    current.value = null; // 新增时重置数据
    // if (!props.dict_ids) {
    //   throw new Error("请先选择字典");
    // }
  },
});

const { visible: showEdit, open: openEdit } = useModal({
  beforeOpen: async (row) => {
    current.value = row; // 设置当前行数据
    // if (!row?.editable) {
    //   throw new Error("没有编辑权限");
    // }
  },
});

const { visible: showView, open: openView } = useModal({
  beforeOpen: async (row) => {
    current.value = row; // 设置当前行数据
  },
});

/** 删除 */
// 替换原有的remove方法
const { action: remove } = useOperator({
  actionConfigs: {
    remove: {
      title: "删除",
      confirmText: "确定要删除{%s}这些数据吗?",
      api: removeDictionary,
      beforeSubmit: (params) => {
        // 可以修改或添加提交参数
        console.log("[DEBUG] beforeSubmit 钩子被调用", params);
        return params; // 必须返回处理后的参数
      },
    },
  },
  // selections,
  reload: query,
  idField: "dict_id",
  idName: "dict_name",
});

// /** 打开编辑弹窗 */
// const openEdit = (row) => {
//   editData.value = row ?? null;
//   showEdit.value = true;
// };

// /** 删除 */
// const remove = () => {
//   const row = current.value;
//   if (!row) {
//     return;
//   }
//   ElMessageBox.confirm(`确定要删除“${row.dict_name}”吗?`, "系统提示", {
//     type: "warning",
//     draggable: true,
//   })
//     .then(() => {
//       const loading = EleMessage.loading({
//         message: "请求中..",
//         plain: true,
//       });
//       removeDictionary(row.dict_id)
//         .then((msg) => {
//           loading.close();
//           EleMessage.success(msg);
//           query();
//         })
//         .catch((e) => {
//           loading.close();
//           EleMessage.error(e.message);
//         });
//     })
//     .catch(() => {});
// };

/** 树过滤方法 */
const filterNode = (value, data) => {
  if (value) {
    return !!(data.dict_name && data.dict_name.includes(value));
  }
  return true;
};

/** 树过滤 */
watch(keywords, (value) => {
  treeRef.value?.filter?.(value);
});

query();
</script>
